
$(document).ready(function(){
	$("#all-box").click(function(){
		$("input[@name='ids']").each(function() {
			$(this).attr("checked", document.getElementById("all-box").checked);
		});
	});
	//list delete
	$('#delete').click(function(){
		if(!checkSelected($("input[@name='ids']"))){
			alert('对不起,请先选中记录!');
			return ;
		}
		if(confirm('您是否确认要删除选中的记录!',0 + 32 + 1,'Information')){
			$('#list-form').submit();
		}
	});	
	

	
	bindRemovePageMessages();

	
	
});

function bindRemovePageMessages(){
	$('#pageErrorMessage button, #pageSuccessMessage button').click( function(){
		removePageMessages();
	});	
}

function removePageMessages(){
	$('#pageErrorMessage, #pageSuccessMessage').remove();
}

function wrapMessage(msg){
	return "<div id='pageSuccessMessage'  style='display: block;'><div class='message'>"+msg+"</div><button style='width: 50px; margin-top: 10px;'>确定</button></div>";
}
function wrapError(err){
	return "<div id='pageErrorMessage'  style='display: block;'><div class='message'>"+err+"</div><button style='width: 50px; margin-top: 10px;'>确定</button></div>";
}

function hidePageMessages(){
	$('#pageErrorMessage, #pageSuccessMessage').hide();
}

function checkSelected(l){
	for(var i=0;i<l.length;i++){
		if(l[i].checked){
			return true;
		}
	}
	return false;
}


var Tail = new Object();
function load_event_monitor(root) {
	var re = /a_(\w+)/;
	var fns = {};
	$(".j", root).each(function(i) {
		var className = this.className;
		var jsname    = className.substring(className.indexOf("j "));

		var m = re.exec(jsname);
		if (m) {
			var f = fns[m[1]];
			if (!f) {
				f = eval("Tail.init_"+m[1]);
				fns[m[1]] = f;
			}
			f && f(this);
		}
	});
}

$(function() {
	load_event_monitor(document);
});



Tail.init_slide_show = function(o){
	$(o).cycle({ 
	    fx:     'scrollUp', 
	    timeout: 6000, 
	    delay:  -2000,
         pager:  '#pager'
	});
}

Tail.init_rec_btn = function(o){
	$(o).click(function(){
		var _ = $(o).attr('id').split('-');
		var rdialog = 'dialog_rec_' + _[1] + '_' + _[2];
		show_dialog($("#"+rdialog).html(),500); 
		load_event_monitor('#dialog');	
	});
}

Tail.init_rec_form = function(form){
	form.onsubmit = function(){
		var url = form.action;
		//var data = "type="+ form.type.value + "&recommendId="+ form.recommendId.value+"&content="+encodeURIComponent(form.content.value) ;
		var recommendId= form.recommendId.value;
		var type= form.type.value;

		//postUrlXMLResponse(url,data);		
        remote_submit_json(this, function(data){
            $('#dialog').html('<div class="loadpop">推荐已提交</div>');
            set_overlay();
            setTimeout(function(){
            	$('#dialog, #overlay').fadeOut(close_dialog);
              	if($(':hidden',form)[0].value == "I"){
                	document.location.reload();
              	}
          	},400);
          	
          	$("#recommend-count-"+type+"-"+recommendId).html(data);
        });
        		
		return false;
	}   
}
Tail.init_ajax_link = function(o){
	$(o).click(function(){
		var div_id = $(o).parent().attr("id");
		showLoading(div_id,true);
		var url = $(o).attr("href");
		getUrlXMLResponseAndFillDiv(url,div_id,ajax_link_callback);
		return false;
	});
}	
function ajax_link_callback(div_id,data){
	load_event_monitor($("#"+div_id));
}

Tail.init_scroll_pane = function(o){
	$(o).jScrollPane({showArrows:true});
}

Tail.init_context_table= function(o){
	$(o).find(".context_table_tl,.context_title").click(function(){
		$(o).find(".context_table_m").toggle();
		$(o).find(".context_table_t").toggleClass("open");
	});
}
Tail.init_hidden_content_list= function(o){
	$(o).find("li").mousemove(function(){
	 	$(this).parent().find("li.current").removeClass("current");
		$(this).addClass("current");
	});
}


Tail.init_switch_city = function(o) {
	$('#city-box ').mouseover(function(){  
		$('#city-box div').show();
	}).
	mouseout(function(){
		$('#city-box div').hide();
	})  
}

Tail.init_top_search = function(o) {
	$('#top_search_type_list_box').mouseover(function(){  
		$('#top_search_type_list').show();
	}).
	mouseout(function(){
		$('#top_search_type_list').hide();
	});
	
	$("#top_search_type_list li").mouseover(function(){  
		$(this).addClass("over");}).mouseout(
        	function(){$(this).removeClass("over");}) 	
    
    $("#top_search_type_list li").click(function(){
    	
    	$("#top_search_type").val($(this).attr("search_type"));
    	$(".search_type_label").html($(this).html());
    	$("#top_search_type_list").hide();
    });
	   
}

Tail.init_toggle = function(o){
	$(o).click(function(){
		//var rid = $(o).attr('id').split('_')[1];
		var toggleId = $(o).attr('toggleid');
		var display = $("#"+toggleId).css("display");
		if(display=='none'){
			$("#"+toggleId).show();
			$(this).find("img").attr("src",cpath+"/images/toggle_2.gif");
		}else{
			$("#"+toggleId).hide();
			$(this).find("img").attr("src",cpath+"/images/toggle_1.gif");
		}
		return false;
	});
}




Tail.init_confirm_ajax_link= function(o) {
	$(o).click(function(){
		var text = $(this).attr('title') || $(this).text();
		var loading = $(this).attr('loading');
		var url = $(this).attr('href');
		if(confirm(text+"?")){
			showLoading(loading);
			getUrlXMLResponseAndFillDiv(url,loading);
		}
		return false;
	});
}

Tail.init_confirm_link = function(o) {
	$(o).click(function(){
		var text = $(this).attr('title') || $(this).text();
		return confirm(text+"?");
	});
}


Tail.init_show_login = function(o){
    $(o).click(function(){
        show_dialog($("#login_box").html(),320);
        $('#overlay').css('z-index',100); //workaround for ff2 bug
        $("#dialog .username").focus()
        $('.pop_reg').click(function(){
            set_cookie({regfromurl:location.href,
                regfromtitle:encodeURIComponent(document.title)})
        })
  
		$(".pop_login_form").validate({
			rules: {
				"j_username": {
					required: true
				},
				"j_password": {
					required: true
				}
			},
			messages: {
				"j_username": {
					required:"*"
				},
				"j_password": {
					required: "*"
				}	
			},		
			submitHandler: function(form) {
				showLoading("login_box_state",true);
				var url = form.action;
				var data = "?j_username="+ form.j_username.value + "&j_password="+ form.j_password.value +"&whence=ajax";
				if(form._spring_security_remember_me){
					if(form._spring_security_remember_me.checked){
						data = data+"&_spring_security_remember_me=true";
					}
				}
				getUrlXMLResponseAndCallback(url+data,loginCallback("login_box_state",o));
				//postUrlXMLResponse(url,data,"loginCallback","login_box_state");
			}
		});	   
        return false;
    });
}

function loginCallback(login_box_state,o){
	return function(data){
		var json = eval("("+data+")");
		
		if(json.success==1){
			//login_state='true';
			
			//var onclick = $(o).attr("onclick");
			//if(onclick){
				//o.click();
				//$('.a_show_login').unbind('click');
	            //$('#dialog').html('<div class="loadpop">登录成功</div>');
	            //set_overlay();
	            //setTimeout(function(){
	            // 	$('#dialog, #overlay').fadeOut(close_dialog);
	          	//},200);	
			//}
			document.location.reload();
			
		}else{
			$("#"+login_box_state).html("<span class='error'>"+json.msg+"</span>");
		}			
	};
}


var show_dialog = function(div,width) {
    if($('#dialog').length) return;
    $('body').prepend('<div id="overlay"></div><div id="dialog"><a class="close" href="javascript:close_dialog();void(0)">X</a></div>');
    $("#dialog").css("width",width+"px");
    if(div != null){
        $('#dialog').append(div);
    }else{
        $('#dialog').html("<div class='loadpop'>load...</div>");
    }
    set_overlay();

}

var close_dialog = function() {
    $('#overlay').unbind('click');
    $('#dialog,#overlay,.bgi').remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE6
        $('body','html').css({height: 'auto', width: 'auto'});
        $('html').css('overflow', '');
    }
    document.onkeydown = '';
    return false;
}


var set_overlay = function(){
    var oheight = ($.browser.msie?11:26),
        dialog=$('#dialog')[0],
        w=dialog.offsetWidth,
        left=(document.body.offsetWidth-w)/2+'px';
    $('#overlay').css({height:dialog.offsetHeight+oheight,width:w+26,left:left});
    dialog.style.left=left;
}



Tail.init_hideme = function(o){
    $(o).click(function(){
        $(this).parent().hide();
    });
}

Tail.init_hide_addfriend= function(o){
    $(o).click(function(){
        $('.hidden_addfriend').hide();
    });
}


Tail.init_show_add_friend = function(o) {
	$(o).click(function(){
		$('.hidden_addfriend').hide();
		var hidelogin = [];
		var dom = $(this);
		while(hidelogin.length == 0 && (dom = dom.parent()) != undefined){
			hidelogin = dom.find('.hidden_addfriend');
		}
		$(hidelogin[0]).slideDown('fast');
		
    });
}


function showLoading(div_id,simple){
	showLoadingObj($("#"+div_id),simple);
}

function showLoadingObj(o,simple){
	var temp_HTML;
	if(simple){
		temp_HTML="<img src="+cpath+"/images/loading_circle_ball.gif>";
	}else{
		temp_HTML="<br><br><br><center><img src="+cpath+"/images/loading_circle_ball.gif></center><br><br><br>";
	}
	$(o).html(temp_HTML);
	document.body.focus();
}

var get_form_fields = function(form) {
	var param = {};
	$(':input', form).each(function(i){
		var name = this.name;
		if (this.type == 'radio') {
			if (this.checked) param[name] = this.value;
        } else if (this.type == 'checkbox') {
			if (this.checked) param[name] = this.value;
        } else if (this.type == 'submit'){ 
            if (/selected/.test(this.className)) param[name] = this.value; 
		} else {
			if (name) param[name] = this.value;
		}
		if(/notnull/.test(this.className) && this.value == ''){
			$(this).prev().addClass('errnotnull');
			param['err'] = 'notnull';
		}
	});
	return param;
}


function loadCommentsCallback(div_id,data){
	load_event_monitor($('#'+div_id));
}

function loadAppVoucherUsersCallback(div_id,data){
	if(data){
		$("#"+div_id).show();
	}
}


function execOnSuccess(stateChangeCallback,opt_successCallback,opt_divId){
	return function(data){
		if(opt_divId){
			stateChangeCallback(data,opt_successCallback,opt_divId);
		}else{
			stateChangeCallback(data,opt_successCallback);
		}
	}
}

function getUrlXMLResponseCallback(data,successCallback,opt_div_id){
	if(successCallback){
		var cb = eval(successCallback);
		cb(opt_div_id,data);
	}	
}

function getUrlXMLResponseCallbackPrependDiv(data,successCallback,div_id){
	$("#"+div_id).prepend(data);
	if(successCallback){
		var cb = eval(successCallback);
		cb(div_id,data);
	}
}

function getUrlXMLResponseCallbackFillDiv(data,successCallback,div_id){
	$("#"+div_id).html(data);
	
	if(successCallback){
		var cb = eval(successCallback);
		cb(div_id,data);
	}
}

function postUrlXMLResponse(url,data,successCallback,opt_div_id){
	postUrl(url,data,true,execOnSuccess(getUrlXMLResponseCallback,successCallback,opt_div_id))
}

function postUrlXMLResponseAndPrependDiv(url,data,div_id,successCallback){
	postUrl(url,data,true,execOnSuccess(getUrlXMLResponseCallbackPrependDiv,successCallback,div_id))
}

function postUrlXMLResponseAndFillDiv(url,data,div_id,successCallback){
	postUrl(url,data,true,execOnSuccess(getUrlXMLResponseCallbackFillDiv,successCallback,div_id))
}

function getUrlXMLResponseAndFillDivSync(url,div_id,opt_successCallback){
	getUrl(url,false,execOnSuccess(getUrlXMLResponseCallbackFillDiv,opt_successCallback,div_id));
}
function getUrlXMLResponseAndFillDiv(url,div_id,opt_successCallback){
	getUrl(url,true,execOnSuccess(getUrlXMLResponseCallbackFillDiv,opt_successCallback,div_id));
}
function getUrlXMLResponseAndCallback(url,successCallback){
	getUrl(url,true,successCallback);
}
function getUrlXMLResponse(url,opt_successCallback){
	getUrl(url,true,execOnSuccess(getUrlXMLResponseCallback,opt_successCallback));
}

var remote_submit_json = function(form, func, disable,result_not_json) {
    var fvalue = get_form_fields(form);
    if(fvalue['err'] == undefined){
        if(disable != false){
            $(':submit',form).attr('disabled', 1);
            $('textarea',form).attr('disabled', 1);
            $('input',form).attr('disabled', 1);
        }
        $.post(form.action, fvalue, function(ret){
            if(!result_not_json){
            	func(eval('('+ret+')'));
            }else{
            	func(ret);
            }
	        if(disable != false){
	            $(':submit',form).attr('disabled', 0);
	            $('textarea',form).attr('disabled', 0);
	            $('input',form).attr('disabled', 0);
	        }            
        });
    }
}

function getUrl(url,async,onSuccessCallback){
	$.ajax({
	   type: "GET",
	   url: url,
	   async:async,
	   data: "r="+getRandom(),
	   success: onSuccessCallback,
	   error:execOnError
	}); 
}

function postUrl(url,data,async,onSuccessCallback){
	data = data+"&r=" +getRandom();
	$.ajax({
	   type: "POST",
	   url: url,
	   async:async,
	   data: data,
	   success: onSuccessCallback,
	   error:execOnError
	}); 
}


function postCommentForOrder(type,comment_form,div_id){
	var form       = $("#"+comment_form)[0];
	var content    = trim(form.content.value);
	if(content.length<2){
		$("#"+comment_form +" .error").html("至少输入两个字符");return ;
	}
	
	var fid        = form.fid.value;
	var shareOrder = form.shareOrder.checked;
	var orderId    = form.orderId.value;
	var rate       = form.rate.value;
	var data = "content="+ content+"&type="+ type +"&fid="+fid + "&shareOrder=" + shareOrder + "&orderId="+orderId+"&rate="+rate;
	var url  = cpath + "/post_comment.jspa";
	showLoading("comment_state",true);
	postUrlXMLResponseAndFillDiv(url,data,div_id);
}



function postComment(type,comment_form,fid,div_id){
	
	if(login_state=='true'){
		var content = trim($('#'+comment_form +" textarea").val());
		if(content.length<2){
			$('#'+comment_form +" .error").html("至少输入两个字符");
			return ;
		}
		$('#'+comment_form +" .error").html("");
		var data = "content="+ content+"&type="+ type +"&fid="+fid;
		var url  = cpath + "/post_comment.jspa";
		
		showLoading("comment_state",true);
		postUrlXMLResponseAndPrependDiv(url,data,div_id,"postCommentCallback");
	}
}

function postCommentCallback(div_id,data){
	$('#comment_state').html("");
	$('#comment_form textarea').val("");
	load_event_monitor($('#'+div_id));
}

function  execOnError(XMLHttpRequest, textStatus, errorThrown) {
	//alert("Error while processing your request.");
	return;
} 


function initTinyMCE(elements){
	tinyMCE.init({
		mode : "exact",
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,cut,copy,paste,|,bullist,numlist,|,outdent,indent,blockquote,hr,removeformat",
		theme_advanced_buttons2 : "undo,redo,|,link,unlink,anchor,image,|,preview,|,forecolor,backcolor,tablecontrols,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,fullscreen",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		theme_advanced_buttons1_add_before : " upload",
		elements : elements,
		language : "ch",
		content_css : "css/content.css",
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}

function initMiniMCE(elements){
	tinyMCE.init({
		mode : "exact",
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontsizeselect,cut,copy,paste,|undo,redo,|,link,unlink,image,|,preview,|,forecolor,backcolor|,charmap,emotions,iespell,media,fullscreen",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		theme_advanced_buttons1_add_before : " upload",
		elements : elements,
		language : "ch",
		content_css : "css/content.css",
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}



/*-------------------------------------------------------*/
function initIndexCalendar(){
	$("#blockA span.available").mouseover(function(){
		
		var obj = $(this)[0];
		var x = getX(obj);
		var y = getY(obj);
		var dayContainerId = $(this).attr("day");
		$("#"+dayContainerId).css("left",x+20);
		$("#"+dayContainerId).css("top",y+10);
		$("#"+dayContainerId).show();
		$(this).css("background","#FFFFCC");
	}).mouseout(function(){
		var dayContainerId = $(this).attr("day");
		$("#"+dayContainerId).hide();
		if($(this).attr("class")!='available current'){
			$(this).css("background","#FFFFFF");
		}
	});
}

function blockAutoScroll(o,content_active){
	var speed=30;
	var c1 = $(content_active).find('.c1')[0];
	var c2 = $(content_active).find('.c2')[0];
	var container = $(o).find('.container')[0];
	c2.innerHTML=c1.innerHTML;
	function Marquee(){
		if(c2.offsetTop-container.scrollTop<=15){
			container.scrollTop-=c1.offsetHeight;
		}
		else{
			container.scrollTop++;
		}
	}
	var MyMar=setInterval(Marquee,speed);
	container.onmouseover=function(){clearInterval(MyMar)}
	container.onmouseout=function(){MyMar=setInterval(Marquee,speed)}
}

Tail.init_tabs = function(o){
	var type         = $(o).attr("type");
	var url          = $(o).attr("url");
	var addScrollbar = $(o).attr("addScrollbar");
	var autoScroll   = $(o).attr("autoScroll");
	if(type=="1"){
		$(o).find(".tab").click(function(){
			click_tab(url,o,$(o).find(".tab.current"),$(this),addScrollbar,autoScroll);
		});		
	}else if(type=="2"){
		$(o).find(".tabs2 li").click(function(){
			click_tab(url,o,$(o).find(".tabs2 li.current"),$(this),addScrollbar,autoScroll);
		});		
	}
}

function click_tab_callback(o,container,content_active,autoScroll,addScrollbar){
	return function(data){
		content_active.html(data);
		if(addScrollbar){
			container.jScrollPane({showArrows:true});
		}
		if(autoScroll) 
			blockAutoScroll(o,content_active);				
	};
}
function click_tab(url,o,over,active,addScrollbar,autoScroll){
	
	var over_tabname   = over.attr("tabname");
	var active_tabname = active.attr("tabname");
	
	var content_over   = $(o).find("."+over_tabname);
	var content_active = $(o).find("."+active_tabname);
	var container      = $(o).find(".container");
	addScrollbar = (addScrollbar=="true");
	autoScroll   = (autoScroll=="true");
	over.removeClass("current");
	active.addClass("current");
	content_over.hide();
	content_active.show();	
	
	if(url.indexOf("?")>0){
		url = url +"&";
	}else{
		url = url +"?";
	}
	url = url +"ckey="+active_tabname;
	
	if(autoScroll) 
		container[0].scrollTop=0;

	if(content_active.attr("load")!="1"){
		showLoadingObj(content_active);
		getUrlXMLResponseAndCallback(url,click_tab_callback(o,container,content_active,autoScroll,addScrollbar));
		content_active.attr("load","1");
	}else{
		if(addScrollbar){
			container.jScrollPane({showArrows:true});
		}
		
		//
		if(active_tabname=='OTHER_CITY_RECOMMEND'){
			$("#OTHER_CITY_RECOMMEND_CONTAINER_WRAP").show();
			$("#OTHER_CITY_RECOMMEND_CONTAINER").jScrollPane({showArrows:true});
		}
	}
}

